package org.saxonextensions.eml.emitter;

import org.saxonextensions.eml.AbstractTestCase;

import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.Transformer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.HashMap;

import net.sf.saxon.Controller;

/**
 * Test EML Emmiter
 *
 * @author Ivan Latysh <ivan@yourmail.com>
 * @version 0.1
 * @since 5-May-2008 2:03:09 PM
 */
public class EMLEmitterUTest extends AbstractTestCase {

  /**
   * Test transformation
   */
  public void testTransform() {
    FileInputStream eml = null;
    FileInputStream xml = null;
    FileOutputStream out = null;
    try {
      try {
        eml = new FileInputStream(new File(home, "/tests/data/eml001.xsl"));
        xml = new FileInputStream(new File(home, "/tests/data/eml001.xml"));
        File outFile = new File(home, "/tests/out/eml001.xsl.out");
        if (outFile.isFile() && outFile.exists()) {
          outFile.delete();
        } else if (!outFile.getParentFile().exists()) {
          outFile.getParentFile().mkdirs();
        }
        outFile.createNewFile();
        out = new FileOutputStream(outFile);
        StreamResult result = new StreamResult(out);
        result.setSystemId(home);
        // parameters
        Map<String, Object> params = new HashMap<String,Object>(1);
        params.put("home", home.getAbsolutePath());
        // run transformation
        transform(new StreamSource(eml), new StreamSource(xml), params, result);
      } finally {
        if (null!=eml) eml.close();
        if (null!=xml) xml.close();
        if (null!=out) out.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }

  /**
   * Test transformation with dev null output resolver
   */
  public void testOutputURIResolver() {
    FileInputStream eml = null;
    FileInputStream xml = null;
    try {
      try {
        eml = new FileInputStream(new File(home, "/tests/data/eml002.xsl"));
        xml = new FileInputStream(new File(home, "/tests/data/eml001.xml"));

        // get a new transformer for given XSLT
        Transformer transformer = factory.newTransformer(new StreamSource(eml));
        // register output URI Resolver
        if (transformer instanceof Controller) {
          ((Controller)transformer).setOutputURIResolver(new ExtendedlOutputResolver());
        }
        // perform the transformation
        transformer.transform(new StreamSource(xml), new DevNullResult());

      } finally {
        if (null!=eml) eml.close();
        if (null!=xml) xml.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }

}
